package com.xian.service;

import com.xian.handler.UserServiceHandler;
import com.xian.util.JSONSerializer;
import com.xian.util.RpcDecoder;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.Date;

@Service("UserService")
public class UserServiceImpl implements UserService {
    public String sayHello(String msg) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String date = format.format(new Date());
        System.out.println(date+" 收到的msg： ---- " + msg);
        return "success";
    }

    public static void startServer(String ip,int port) throws InterruptedException {
        //1.创建两个线程池
        NioEventLoopGroup bossGroup =  new NioEventLoopGroup();
        NioEventLoopGroup workGroup =  new NioEventLoopGroup();

        //2.创建服务端的启动引导对象
        ServerBootstrap serverBootstrap = new ServerBootstrap();

        //3.配置启动引导对象
        serverBootstrap.group(bossGroup,workGroup)
                //设置通道
                .channel(NioServerSocketChannel.class)
                //创建监听channel
                .childHandler(new ChannelInitializer<NioSocketChannel>() {
                    protected void initChannel(NioSocketChannel nioSocketChannel) throws Exception {
                        //获取管道对象
                        ChannelPipeline pipeline = nioSocketChannel.pipeline();

                        // 设置编码
                        pipeline.addLast(new StringEncoder());
                        pipeline.addLast(new RpcDecoder(RpcRequest.class, new JSONSerializer()));
                        //自定义一个channleHandel 添加到同道中
                        pipeline.addLast(new UserServiceHandler());
                    }
                });

        //4.绑定端口
           serverBootstrap.bind(ip,port).sync();
    }


}
